package com.ctrip.business;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ctrip.utils.SymmetricEncoder;
import com.go.commons.dto.Page;
import com.go.commons.utils.HttpClientUtil;
import com.go.commons.utils.MD5;
import com.go.commons.utils.StringUtils;
import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.entity.ContentType;
import org.apache.http.message.BasicHeader;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

/**
 * https://vbooking.ctrip.com/VBKH5/
 * https://vbooking.ctrip.com/dingzhi/RobApp/GetRobRequireList?_fxpcqlniredt=09031124110231317451
 *
 {pageIndex: 1, pageSize: 5, orderType: "GrabOrder", isAll: false, contentType: "json"}
 contentType
 :
 "json"
 isAll
 :
 false
 orderType
 :
 "GrabOrder"
 pageIndex
 :
 1
 pageSize
 :
 5
 */
@Slf4j
public class H5OrderService {
    public static JSONArray listWaitingOrders(Page page, boolean isAll)  {
        Map<String, Object> params = new HashMap<>();
        params.put("contentType", "json");
        params.put("isAll", isAll);
        params.put("orderType", "GrabOrder");
        params.put("pageIndex", page.getCurPage());
        params.put("pageSize", page.getPageSize());
        try {
            String response = HttpClientUtil.postNotForm("https://vbooking.ctrip.com/dingzhi/RobApp/GetRobRequireList?_fxpcqlniredt=09031124110231317451", JSON.toJSONString(params), ContentType.APPLICATION_JSON, new Header[]{new BasicHeader("Cookie", UserService.cookie)});
            JSONObject jsonObject = JSON.parseObject(response).getJSONObject("Data");
            page.setTotalRow(jsonObject.getInteger("TotalCount"));
            JSONArray array= jsonObject.getJSONArray("Items");
            if (array != null) {
                return array;
            }
        } catch (Exception e) {
            log.error(e.toString(),e);
        }
        return new JSONArray();
    }

    /**
     * @param requireDetailID
     * @return
     */
    public static boolean grabOrder(String requireDetailID) throws Exception {
        Map<String, Object> params = new HashMap<>();
        params.put("contentType", "json");
        params.put("jsVersion", "2.3.28");
        params.put("requireDetailId", requireDetailID);
        params.put("verifyToken", getVerifyToken());
        String response = HttpClientUtil.postNotForm("https://vbooking.ctrip.com/dingzhi/RobApp/ConfirmRob?_fxpcqlniredt=09031124110231317451",
                JSON.toJSONString(params), ContentType.APPLICATION_JSON, new Header[]{new BasicHeader("Cookie", UserService.cookie)});
        log.info("抢单返回：{}", response);
        return true;
    }

    public static String getVerifyToken() throws Exception {
        String resp = HttpClientUtil.get("https://m.ctrip.com/restapi/infosec/captcha/verify_slider?callback=captcha011821127061895842&appid=100000313&business_site=dingzhi_roborderlist_limit&version=2.3.28&verify_msg=7VXU0t%2BcUmqWVGg8TnFxCnwJTs4V3Vcm3TjXTtxMc3vbAyB0hVarcDBOQC4iVe8TF0g4709IC4cZE7hdHsmjPpvvAKULFrvQTApjORiTgOoLSvfYFyrPAP74QvFpVsxCoJZP6jEc2Whdo83uNgyvQpVElr7C0749gdgc1B%2B0p0UOlcj%2BsxQDeG89zvqijW7lZFsaCbpk3v%2FmgOY8%2FCgAAczCX42RVumvDlhdB2ga2AO3mjx9w1XdzlOd67bSas%2FaH52fMt7KCG3AviF4k0cEl1fGQQbBZ9dospubwqirdGxJSWNdY2eRoBalQAXqPdSo8zPdqK5d4is9Hy8aKtgDkAvqcUEG6WgVIzq8HNI1rMz%2FRIPIuq1Bkh%2BlehL%2BNr1O%2F2JIFia8es6429k4%2BOqye5oBOFZtxUCyJFrOihcGFbtCkhEYhfjxnNT4x5SwKwTLOvfMk%2FQSkGoSW9ghoSdwUtoYMzobFR7H3NOPl6aMMonWMcfheOq8ECnUM7ZiC9SaUaBXzh0FWAbEQmPSyyTwcjIkWHYrok1hcumagY9EZ7mRpYycrEZhUbdL05sE1BVn%2BTMX%2FUyhYVG2%2FvS3WajIubnuCCIRdp%2BZjorw2tpWyB%2BCoulRJGWKPNH5YQIPcnNtcyAlM3fivmbzYpW8Pk9Ahtma6GUzV6iVmKJwRtzXgECbkRPw2K1pZWs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D&extend_param=cmNTBi3Wze0GrsQdWKxLLp0NkDkRRA%2F1eHyZmwUcgNVykZYX7CspSBuEw6FDF9Y19HGSwnh4wU9Zy%2Fs0TkRwXBshMQxbFQ8GX63BI%2BkpGpSefUAWujEKDCGtEw4O10cVIocwQPVsMh15z0SIH1KiLjwx4Rn%2F2UaU7yyDy6T9SiqeLP7nFVEZxhfA7y2s%2FdIQZqqT8fJ4WzKhq9JeAKzDazJknu1a0jCK9%2FnzmB%2FMk8w%3D&sign=5ab18b4697269d156ee751a3a21b4e0f", new Header[]{new BasicHeader("Cookie", UserService.cookie)});
        if (StringUtils.isNotEmpty(resp)) {
            resp = resp.substring(resp.indexOf('(') + 1, resp.length() - 1);
            JSONObject json = JSON.parseObject(resp);
            if (json.getIntValue("code") == 0) {
                return json.getJSONObject("result").getString("token");
            }
        }
        return null;
    }
    public static String getToken() throws UnsupportedEncodingException, Base64DecodingException {
//        callback:captcha011821127061895842
//        verify_msg:7VXU0t+cUmqWVGg8TnFxCnwJTs4V3Vcm3TjXTtxMc3vbAyB0hVarcDBOQC4iVe8TF0g4709IC4cZE7hdHsmjPpvvAKULFrvQTApjORiTgOoLSvfYFyrPAP74QvFpVsxCoJZP6jEc2Whdo83uNgyvQpVElr7C0749gdgc1B+0p0UOlcj+sxQDeG89zvqijW7lZFsaCbpk3v/mgOY8/CgAAczCX42RVumvDlhdB2ga2AO3mjx9w1XdzlOd67bSas/aH52fMt7KCG3AviF4k0cEl1fGQQbBZ9dospubwqirdGxJSWNdY2eRoBalQAXqPdSo8zPdqK5d4is9Hy8aKtgDkAvqcUEG6WgVIzq8HNI1rMz/RIPIuq1Bkh+lehL+Nr1O/2JIFia8es6429k4+Oqye5oBOFZtxUCyJFrOihcGFbtCkhEYhfjxnNT4x5SwKwTLOvfMk/QSkGoSW9ghoSdwUtoYMzobFR7H3NOPl6aMMonWMcfheOq8ECnUM7ZiC9SaUaBXzh0FWAbEQmPSyyTwcjIkWHYrok1hcumagY9EZ7mRpYycrEZhUbdL05sE1BVn+TMX/UyhYVG2/vS3WajIubnuCCIRdp+Zjorw2tpWyB+CoulRJGWKPNH5YQIPcnNtcyAlM3fivmbzYpW8Pk9Ahtma6GUzV6iVmKJwRtzXgECbkRPw2K1pZWsQNsLSVM8fGAaqJZLAwYHQkxcKO2npXV5EQ/Os+A5fieAHGCBeNYQlGIwaJVF2lxgKkTq15YTdIRv5Ui/Xz2kej5sIPRDdsPggWQMWhgVM45aQ9ESpn4unIMfW4AKwGJXUPRxCHKeGW50Az4CVrck1lqT3lRWGtJbbCvRGR++4hQSHmW9fGhV9uJYkAFb7A8t3ixUCKWnSY9OeGFUZYAD6mPeNPTPOWfGD1fm4KHXRTAYgY88ZUr8=
        String appid = "100000313";
        String business_site = "dingzhi_roborderlist_limit";
        String version = "2.3.28";
        String verify_msg = "7VXU0t+cUmqWVGg8TnFxCnwJTs4V3Vcm3TjXTtxMc3vbAyB0hVarcDBOQC4iVe8TF0g4709IC4cZE7hdHsmjPpvvAKULFrvQTApjORiTgOoLSvfYFyrPAP74QvFpVsxCoJZP6jEc2Whdo83uNgyvQpVElr7C0749gdgc1B+0p0UOlcj+sxQDeG89zvqijW7lZFsaCbpk3v/mgOY8/CgAAczCX42RVumvDlhdB2ga2AO3mjx9w1XdzlOd67bSas/aH52fMt7KCG3AviF4k0cEl1fGQQbBZ9dospubwqirdGxJSWNdY2eRoBalQAXqPdSo8zPdqK5d4is9Hy8aKtgDkAvqcUEG6WgVIzq8HNI1rMz/RIPIuq1Bkh+lehL+Nr1O/2JIFia8es6429k4+Oqye5oBOFZtxUCyJFrOihcGFbtCkhEYhfjxnNT4x5SwKwTLOvfMk/QSkGoSW9ghoSdwUtoYMzobFR7H3NOPl6aMMonWMcfheOq8ECnUM7ZiC9SaUaBXzh0FWAbEQmPSyyTwcjIkWHYrok1hcumagY9EZ7mRpYycrEZhUbdL05sE1BVn+TMX/UyhYVG2/vS3WajIubnuCCIRdp+Zjorw2tpWyB+CoulRJGWKPNH5YQIPc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3Wze0GrsQdWKxLLp0NkDkRRA/1eHyZmwUcgNVykZYX7CspSBuEw6FDF9Y19HGSwnh4wU9Zy/s0TkRwXBshMQxbFQ8GX63BI+kpGpSefUAWujEKDCGtEw4O10cVIocwQPVsMh15z0SIH1KiLjwx4Rn/2UaU7yyDy6T9SiqeLP7nFVEZxhfA7y2s/dIQZqqT8fJ4WzKhq9JeAKzDazJknu1a0jCK9/nzmB/Mk8w=";
        System.out.println(SymmetricEncoder.decrypt("3d70d6aee9810adac87eac0a78ba69be",URLDecoder.decode(verify_msg)));
        System.out.println(SymmetricEncoder.decrypt("3d70d6aee9810adac87eac0a78ba69be",dimensions));
        System.out.println(SymmetricEncoder.decrypt("3d70d6aee9810adac87eac0a78ba69be",extend_param));
        StringBuilder sb = new StringBuilder()
                .append("appid=").append(appid)
                .append("&business_site").append(business_site)
                .append("&version=").append(version)
                .append("&verify_msg=").append(URLDecoder.decode(verify_msg,"GBK"))
                .append("&dimensions=").append(URLDecoder.decode(dimensions,"GBK"))
                .append("&extend_param=").append(URLDecoder.decode(extend_param,"GBK"));
        System.out.println(MD5.encodeMD5(sb.toString()));
        return null;
    }

    public static void main(String[] args) throws Exception {
        while (true) {
            try {
                JSONArray array = listWaitingOrders(new Page(5, 1), false);
                if (array != null && array.size() > 0) {
                    for (int i=0;i<array.size();i++) {
                        JSONObject order = array.getJSONObject(i);
                        String requireDetailID=order.getString("RequireDetailID");
                        grabOrder(requireDetailID);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


}
